<?php
function array_length($arr){
    $length = 0;
    foreach($arr as $key =>$value){
            $length++;
    }
    return $length;
}
function array_implode($arr,$needle=','){
    $length = array_length($arr);
    $str = $needle;
    $i = 0;
    while($i<$length){
        $inst = $arr[$i]; 
        //$str .=$interests[$i];
        $str = $str . $inst.$needle;
        $i++;
    }
    return $str;
}
$hasError=false; 
//检查用户名
//必须填写
//至少三个字符
//最多五个字符
//字母开头,字母数字下划线
$username = trim($_POST["Username"]);
if(!$username) {
    echo "用户名必须填写<br/>";
    $hasError = true;
}else {
    $len = strlen($username);
    if($len<3){
        echo "用户名至少要有三个字符<br/>";
        $hasError = true;
    }else if($len>5){
        echo "用户名最多五个字符";
        $hasError = true;
    }else if(!preg_match('/^[a-zA-Z0-9_]*$/',$username)){
        echo "格式不符合要求";
        $hasError = true;
    }
}

//检查密码
//必须填写
//至少三个字符
//最多五个字符
$password = trim($_POST["Password"]);
if(!$password) {
    echo "密码必须填写<br/>";
    $hasError=true;
}else {
    $len = strlen($password);
    if($len<3){
        echo "密码至少三个字符<br/>";
        $hasError = true;
    }else if($len>5){
        echo "密码最多五个字符<br/>";
        $hasError = true;
    }
}

$gender = $_POST['Gender'];
if($gender == 'male') $gender=1;
else if($gender =='female') $gender = 0;
else $gender = -1;
 //年龄
//可不填写
//必须是数字
$age = trim($_POST['Age']);
if($age){
    // '/^\d+$/'
    $ageNum = intval($age);
    if(!$ageNum || $ageNum <=0 || $ageNum>200){
        echo "请填写正确的年龄<br/>";
        $hasError = true;
    }

}

$interests = $_POST["Interests"];
$length = array_length($interests);
if($length<2){
    echo"兴趣必须填写2个<br/>";
    $hasError = true;
}else if($length>3){
    echo "兴趣最多填三个<br/>";
    $hasError = true;
}
$interestStr = array_implode($interests,"|");
$province = $_POST["Province"];
$intro = $_POST["Intro"];

if(!$hasError){
    $sql = "INSERT INTO `Account` (`Username`, `Password`,`Gender`,`Interests`,`Province`,`Intro`)VALUES('$username','$password',
    '$gender','$interestStr','$province','$intro')";
    echo $sql;

    $sqli = new mysqli("localhost","root","","myblog");
    $sqli ->query($sql);
    echo "注册成功！<br/>";
}

if(!$hasError) echo "检查成功<br/>";


echo "<a href='login.html'>登录</a>";

?>
